import React, { useState } from 'react';
import { updateRecipe, deleteRecipe } from '../services/api';
import ImageUploader from './ImageUploader';
import styles from './RecipeCard.module.css'; // Import CSS Module

const RecipeCard = ({ recipe, onRecipeDeleted, onRecipeUpdated }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedRecipe, setEditedRecipe] = useState({ ...recipe });

  const handleDelete = async () => {
    if (window.confirm(`您确定要删除 "${recipe.dish_name}" 吗？`)) {
      try {
        await deleteRecipe(recipe.id);
        onRecipeDeleted(recipe.id);
      } catch (error) {
        console.error('Failed to delete recipe:', error);
        alert('删除食谱失败。');
      }
    }
  };

  const handleUpdate = async () => {
    // Filter out empty strings from ingredients and method before updating
    const recipeToUpdate = {
      ...editedRecipe,
      ingredients: editedRecipe.ingredients.filter(line => line.trim() !== ''),
      method: editedRecipe.method.filter(line => line.trim() !== ''),
    };

    try {
      const response = await updateRecipe(recipe.id, recipeToUpdate);
      onRecipeUpdated(response.data);
      setIsEditing(false);
    } catch (error) {
      console.error('Failed to update recipe:', error);
      alert('更新食谱失败。');
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setEditedRecipe({ ...editedRecipe, [name]: value });
  };
  
  const handleArrayChange = (e, field) => {
    const { value } = e.target;
    // Split by any newline character and filter out empty strings.
    const updatedArray = value.split(/\n+/).filter(line => line.trim() !== '');
    setEditedRecipe({ ...editedRecipe, [field]: updatedArray });
  };

  const handleImageUpload = (imageUrl) => {
    setEditedRecipe({
      ...editedRecipe,
      image_urls: [...editedRecipe.image_urls, imageUrl],
    });
  };

  const handleImageDelete = (imageUrlToDelete) => {
    setEditedRecipe({
      ...editedRecipe,
      image_urls: editedRecipe.image_urls.filter(url => url !== imageUrlToDelete),
    });
  };

  if (isEditing) {
    return (
      <div className={styles.card}>
        <input
          type="text"
          name="dish_name"
          value={editedRecipe.dish_name}
          onChange={handleInputChange}
          className={`form-control ${styles.title}`}
        />
        <h4 className={styles.sectionTitle}>配料</h4>
        <textarea
          name="ingredients"
          value={editedRecipe.ingredients.join('\n')}
          onChange={(e) => handleArrayChange(e, 'ingredients')}
          className="form-control"
        />
        <h4 className={styles.sectionTitle}>烹饪方法</h4>
        <textarea
          name="method"
          value={editedRecipe.method.join('\n')}
          onChange={(e) => handleArrayChange(e, 'method')}
          className="form-control"
        />
        <h4 className={styles.sectionTitle}>图片</h4>
        <div className={styles.imageGallery}>
          {editedRecipe.image_urls.map((url, index) => (
            <div key={index} className={styles.imageContainer}>
              <img src={url} alt="" className={styles.image} />
              <button onClick={() => handleImageDelete(url)} className={styles.deleteImageBtn}>×</button>
            </div>
          ))}
        </div>
        <ImageUploader onUploadSuccess={handleImageUpload} />
        <div className={styles.buttonContainer}>
          <button onClick={handleUpdate} className="btn btn-success">保存更改</button>
          <button onClick={() => setIsEditing(false)} className="btn btn-secondary">取消</button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.card}>
      <h2 className={styles.title}>{recipe.dish_name}</h2>
      <p className={styles.date}>记录于: {new Date(recipe.log_date).toLocaleDateString()}</p>
      
      {recipe.image_urls && recipe.image_urls.length > 0 && (
        <div className={styles.imageGallery}>
          {recipe.image_urls.map((url, index) => (
            <a href={url} target="_blank" rel="noopener noreferrer" key={index} className={styles.imageContainer}>
              <img src={url} alt={`${recipe.dish_name} ${index + 1}`} className={styles.image} />
            </a>
          ))}
        </div>
      )}

      <h3 className={styles.sectionTitle}>配料</h3>
      <ul className={styles.list}>{recipe.ingredients.map((item, index) => <li key={index}>{item}</li>)}</ul>
      
      <h3 className={styles.sectionTitle}>烹饪方法</h3>
      <ol className={styles.list}>{recipe.method.map((step, index) => <li key={index}>{step}</li>)}</ol>
      
      {recipe.comment && (
        <>
          <h3 className={styles.sectionTitle}>评论</h3>
          <p>{recipe.comment}</p>
        </>
      )}
      
      {recipe.self_critique && (
        <>
          <h3 className={styles.sectionTitle}>自我评价</h3>
          <p>{recipe.self_critique}</p>
        </>
      )}

      <div className={styles.buttonContainer}>
        <button onClick={() => setIsEditing(true)} className="btn btn-primary">编辑</button>
        <button onClick={handleDelete} className="btn btn-danger">删除</button>
      </div>
    </div>
  );
};

export default RecipeCard;
